import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:hm_pda_app/config/http_request.dart';

// 文件数据类，包含文件内容和元信息
class FileData {
  final Uint8List bytes;
  final String name;
  final String mimeType;
  final int size;

  FileData({
    required this.bytes,
    required this.name,
    required this.mimeType,
    required this.size,
  });

  @override
  String toString() {
    return 'FileData{name: $name, size: $size bytes, mimeType: $mimeType}';
  }
}
class ImgData {
 final String fileName;
 final num fileSize;
 final String ossId;
 final String url;
 ImgData({
 required this.fileName,
 required this.fileSize,
 required this.ossId,
 required this.url
 });
 factory ImgData.form(Map<String, dynamic> json) {
    return ImgData(
      fileName: json['fileName'] as String,
      url: json['url'] as String,
      fileSize: json['fileSize'] as num,
      ossId: json['ossId'] as String,
    );
  }
  // json格式化成自己想要的格式
  Map<String, dynamic> toJson() {
    return {
     'url': url,
      'attachmentName': fileName,
      'fileName':fileName,
      'ossId':ossId,
      'fileSize':fileSize,
      'attachmentUrl':url,
      'attachmentSize':fileSize

    };
  }
}

class ImageUploadHelper {
  static final ImagePicker _picker = ImagePicker();

  // 显示选择图片来源的底部弹窗
  static Future<File?> showImageSourceDialog(BuildContext context) async {
    return showModalBottomSheet<File?>(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Wrap(
            children: [
              ListTile(
                leading: const Icon(Icons.photo_camera),
                title: const Text('拍照'),
                onTap: () async {
                  final file = await _pickImageFromCamera();
                  Navigator.pop(context, file);
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text('从相册选择'),
                onTap: () async {
                  // pickMultipleImages 选择多张
                  // _pickImageFromGallery 选单张
                  final file = await pickMultipleImages();
                  Navigator.pop(context, file);
                },
              ),
              ListTile(
                leading: const Icon(Icons.cancel),
                title: const Text('取消'),
                onTap: () => Navigator.pop(context),
              ),
            ],
          ),
        );
      },
    );
  }

  // 从相机拍照
  static Future<File?> _pickImageFromCamera() async {
    try {
      // 检查相机权限
      final cameraStatus = await Permission.camera.request();
      if (cameraStatus != PermissionStatus.granted) {
        throw Exception('相机权限被拒绝');
      }

      final XFile? image = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 80,
        maxWidth: 1920,
        maxHeight: 1080,
      );

      if (image != null) {
        return File(image.path);
      }
      return null;
    } catch (e) {
      debugPrint('拍照失败: $e');
      return null;
    }
  }

  // 获取Android版本
  static Future<int> _getAndroidVersion() async {
    if (Platform.isAndroid) {
      // await Permission.storage.serviceStatus;
      // 这里简化处理，实际项目中可以使用device_info_plus包获取准确版本
      return 30; // 默认返回30，实际应该获取真实版本
    }
    return 0;
  }

  // 选择多张图片 - 返回File对象（基于路径）
  static Future<List<File>> pickMultipleImages() async {
    try {
      PermissionStatus storageStatus;
      if (Platform.isAndroid) {
        if (await _getAndroidVersion() >= 33) {
          storageStatus = await Permission.photos.request();
        } else {
          storageStatus = await Permission.storage.request();
        }
      } else {
        storageStatus = await Permission.photos.request();
      }

      if (storageStatus != PermissionStatus.granted) {
        throw Exception('存储权限被拒绝');
      }

      final List<XFile> images = await _picker.pickMultiImage(
        imageQuality: 80,
        maxWidth: 1920,
        maxHeight: 1080,
      );

      return images.map((image) => File(image.path)).toList();
    } catch (e) {
      debugPrint('选择多张图片失败: $e');
      return [];
    }
  }

  // 选择多张图片 - 直接获取文件内容，不依赖路径
  static Future<List<FileData>> pickMultipleImagesAsFileData() async {
    try {
      PermissionStatus storageStatus;
      if (Platform.isAndroid) {
        if (await _getAndroidVersion() >= 33) {
          storageStatus = await Permission.photos.request();
        } else {
          storageStatus = await Permission.storage.request();
        }
      } else {
        storageStatus = await Permission.photos.request();
      }

      if (storageStatus != PermissionStatus.granted) {
        throw Exception('存储权限被拒绝');
      }

      final List<XFile> images = await _picker.pickMultiImage(
        imageQuality: 80,
        maxWidth: 1920,
        maxHeight: 1080,
      );

      List<FileData> fileDataList = [];

      for (XFile image in images) {
        try {
          // 直接读取文件内容到内存
          final Uint8List bytes = await image.readAsBytes();
          final String fileName = image.name.isNotEmpty
              ? image.name
              : image.path.split('/').last;
          final String mimeType = image.mimeType ?? 'image/jpeg';

          debugPrint(
            '读取文件: $fileName, 大小: ${bytes.length} bytes, MIME类型: $mimeType',
          );

          fileDataList.add(
            FileData(
              bytes: bytes,
              name: fileName,
              mimeType: mimeType,
              size: bytes.length,
            ),
          );
        } catch (e) {
          debugPrint('读取文件失败: ${image.path}, 错误: $e');
        }
      }

      debugPrint('成功读取 ${fileDataList.length} 个文件到内存');
      return fileDataList;
    } catch (e) {
      debugPrint('选择图片失败: $e');
      return [];
    }
  }

  // 文件上传方法 - 使用File对象（基于路径）
  static Future<ImgData?> uploadFile(File file) async {
    try {
      debugPrint('开始上传文件: ${file.path}');
      debugPrint('文件大小: ${await file.length()} bytes');

      final fileName = file.path.split('/').last;
      debugPrint('文件名: $fileName');

      // 使用 HttpUtil.uploadFile 上传文件
      final response = await HttpUtil.uploadFile(
        '/resource/oss/upload',
        file: file,
        fileName: fileName,
      );

      debugPrint('上传响应: ${response.toString()}');

      // 检查上传是否成功
      if (response.success) {
        return ImgData.form(response.data);
        // // 根据实际API响应格式解析URL
        // if (response.data != null) {
        //   // 如果data是Map类型，尝试获取url字段
        //   if (response.data is Map<String, dynamic>) {
        //     final dataMap = response.data as Map<String, dynamic>;
        //     return dataMap['url'] as String?;
        //   }
        //   // 如果data直接是URL字符串
        //   else if (response.data is String) {
        //     return response.data as String;
        //   }
        // }

        // // 如果没有找到URL，返回一个模拟的URL（用于测试）
        // debugPrint('⚠️ 未找到返回的URL，使用模拟URL');
        // return 'https://example.com/uploads/$fileName';
      } else {
        debugPrint('❌ 上传失败: ${response.message}');
        return null;
      }
    } catch (e) {
      debugPrint('文件上传失败: $e');
      return null;
    }
  }

  // 文件上传方法 - 使用FileData对象（直接使用文件内容）
  static Future<ImgData?> uploadFileData(FileData fileData) async {
    try {
      debugPrint('开始上传文件: ${fileData.name}');
      debugPrint('文件大小: ${fileData.size} bytes');
      debugPrint('MIME类型: ${fileData.mimeType}');

      // 使用 HttpUtil.upload 直接上传文件字节
      final response = await HttpUtil.upload(
        '/resource/oss/upload',
        fileData.bytes,
        fileName: fileData.name,
        headers: {'Content-Type': 'multipart/form-data'},
      );

      debugPrint('上传响应: ${response.toString()}');

      // 检查上传是否成功
      if (response.success) {
        // 根据实际API响应格式解析URL
        // if (response.data != null) {
        //   // 如果data是Map类型，尝试获取url字段
        //   if (response.data is Map<String, dynamic>) {
        //     final dataMap = response.data as Map<String, dynamic>;
        //     return dataMap['url'] as String?;
        //   }
        //   // 如果data直接是URL字符串
        //   else if (response.data is String) {
        //     return response.data as String;
        //   }
        // }
        print('shuju--${response.data}');
         return ImgData.form(response.data);
        // 如果没有找到URL，返回一个模拟的URL（用于测试）
      //  debugPrint('⚠️ 未找到返回的URL，使用模拟URL');
       // return 'https://example.com/uploads/${fileData.name}';
      } else {
        debugPrint('❌ 上传失败: ${response.message}');
        return null;
      }
    } catch (e) {
      debugPrint('文件上传失败: $e');
      return null;
    }
  }
}

// 图片上传状态管理类
class ImageUploadNotifier extends ChangeNotifier {
  List<File>? _selectedImages;
  List<FileData>? _selectedFileData;
  final List<ImgData> _uploadedUrls = [];
  bool _isUploading = false;

  // 添加公共getter方法供外部访问
  List<File>? get selectedImages => _selectedImages;
  List<FileData>? get selectedFileData => _selectedFileData;
  // 返回已上传图片URL的不可修改列表副本，防止外部直接修改内部状态
  List<ImgData> get uploadedUrls => List.unmodifiable(_uploadedUrls);
  bool get isUploading => _isUploading;

  // 添加公共方法供外部设置选中的图片
  void setSelectedImages(List<File>? images) {
    _selectedImages = images;
    notifyListeners();
  }

  void setSelectedFileData(List<FileData>? fileData) {
    _selectedFileData = fileData;
    notifyListeners();
  }

  // 原有方法 - 使用File对象（基于路径）
  Future<void> selectAndUploadImages() async {
    final List<File> images = await ImageUploadHelper.pickMultipleImages();

    if (images.isNotEmpty) {
      _selectedImages = images;
      _isUploading = true;
      notifyListeners();

      debugPrint('开始上传，选中图片数量：${_selectedImages?.length}');

      for (File image in images) {
        final ImgData? uploadedUrl = await ImageUploadHelper.uploadFile(image);
        if (uploadedUrl!.url.isNotEmpty ) {
          _uploadedUrls.add(uploadedUrl);
          notifyListeners(); // 每上传一张图片就通知一次
          debugPrint('上传完成，已上传图片数量：${uploadedUrls.length}');
        }
      }

      _isUploading = false;
      notifyListeners();
      debugPrint('所有图片上传完成');
    }
  }

  // 新方法 - 使用FileData对象（直接使用文件内容，不依赖路径）
  Future<void> selectAndUploadImagesAsFileData() async {
    final List<FileData> fileDataList =
        await ImageUploadHelper.pickMultipleImagesAsFileData();

    if (fileDataList.isNotEmpty) {
      _selectedFileData = fileDataList;
      _isUploading = true;
      notifyListeners();

      debugPrint('开始上传，选中文件数量：${_selectedFileData?.length}');
      debugPrint('文件详情：');
      for (var fileData in fileDataList) {
        debugPrint('  - ${fileData.toString()}');
      }

      for (FileData fileData in fileDataList) {
        final ImgData? uploadedUrl = await ImageUploadHelper.uploadFileData(
          fileData,
        );
        if (uploadedUrl!.url.isNotEmpty) {
          _uploadedUrls.add(uploadedUrl);
          notifyListeners(); // 每上传一张图片就通知一次
          debugPrint('上传完成，已上传图片数量：${uploadedUrls.length}');
        }
      }

      _isUploading = false;
      notifyListeners();
      debugPrint('所有图片上传完成');
    }
  }

  void removeUploadedUrl(int index) {
    if (index >= 0 && index < _uploadedUrls.length) {
      _uploadedUrls.removeAt(index);
      notifyListeners();
    }
  }

  void clearAll() {
    _selectedImages = null;
    _uploadedUrls.clear();
    _isUploading = false;
    notifyListeners();
  }
}

class ImageUploadWidget extends StatelessWidget {
  final Function(List<String>)? onImagesChanged;

  const ImageUploadWidget({super.key, this.onImagesChanged});



  // 使用FileData的方法（获取完整文件内容，不依赖路径）
  Future<void> _selectAndUploadImageAsFileData(BuildContext context) async {
    final notifier = context.read<ImageUploadNotifier>();
    await notifier.selectAndUploadImagesAsFileData();

    if (context.mounted) {
      if (notifier.uploadedUrls.isNotEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('成功上传${notifier.uploadedUrls.length}张图片！'), duration: Duration(seconds: 1),),
        );
      } else {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('图片上传失败！')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ImageUploadNotifier>(
      builder: (context, notifier, child) {
        return Column(
          children: [
            // 使用新的FileData方法（获取完整文件内容，不依赖路径）
            ElevatedButton(
              onPressed: notifier.isUploading
                  ? null
                  : () => _selectAndUploadImageAsFileData(context),
              child: notifier.isUploading
                  ? const CircularProgressIndicator()
                  : const Text('选择并上传图片'),
            ),

            // 可选：添加一个按钮来使用原有的基于路径的方法
            const SizedBox(height: 8),

            if (notifier.uploadedUrls.isNotEmpty)
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text('已上传${notifier.uploadedUrls.length}张图片'),
              ),
          ],
        );
      },
    );
  }
}
